
import {config} from './config';
import tools from '../tools'
var baseURL = config.baseURL

/**
 * 生成sign
 */
var self
function request(api, method, header, params, success,errMsg, retryCount = 0){
	// params.app_key=appKey
	var tou={}
	let token = uni.getStorageSync('token');
	if(token!=""){
		// params.token=token
		tou={Authorization: token}
	}
    const that = this
	const requestTask = uni.request({
        url: baseURL + api,
        method: method,
        header: tou,
        data: params,
		dataType:"json",
        success: function(res) {
            if(res.data.code==1000){
				success(res.data)
			} else if (res.data.code === 401 && retryCount < 1) { // 假设 401 表示 token 过期
                // 尝试刷新token
                const refreshToken = uni.getStorageSync('refreshToken');
                if (refreshToken) {
                    tools.refreshToken();
                    // 等待一小段时间让token刷新完成
                    setTimeout(() => {
                        const newToken = uni.getStorageSync('token');
                        if (newToken) {
                            const newHeader = { Authorization: newToken };
                            // 用新 token 重新发起原请求
                            request(api, method, newHeader, params, success, errMsg, retryCount + 1);
                        } else {
                            // token刷新失败，检查是否已在登录页或允许未登录访问的页面，避免重复跳转
                            const pages = getCurrentPages();
                            const currentPage = pages[pages.length - 1];
                            const currentPath = currentPage.route;
                            // 允许未登录访问的页面列表：首页、店铺、我的
                            const allowUnloginPages = ['pages/index/index2', 'pages/index/report', 'pages/index/mine'];
                            if (currentPath !== 'pages/index/login' && !allowUnloginPages.includes(currentPath)) {
                                tools.routerTo('/pages/index/login', 'navigateTo', 'none');
                            }
                        }
                    }, 500);
                    return;
                }
            } else if (res.data.code === 1001 && res.data.message === '登录失效~') {
                console.log('requestTask', tools)
                // 检查是否已在登录页或允许未登录访问的页面，避免重复跳转
                const pages = getCurrentPages();
                const currentPage = pages[pages.length - 1];
                const currentPath = currentPage.route;
                // 允许未登录访问的页面列表：首页、店铺、我的
                const allowUnloginPages = ['pages/index/index2', 'pages/index/report', 'pages/index/mine'];
                if (currentPath !== 'pages/index/login' && !allowUnloginPages.includes(currentPath)) {
                    tools.routerTo('/pages/index/login', 'navigateTo', 'none');
                }
                return false;
            } else {
				if(errMsg){
					errMsg(res.data)
				}
			}
			
        },
        fail: function(){
			uni.hideLoading();
            uni.showToast({
                icon: "none",
                title: "网络连接异常，请稍后重试"
            })
        }
    })
	
}
// let token = uni.getStorageSync('token');
var GET_METHOD = "GET"
var HEADER

function get(api, params, success,errMsg){
    request(api, GET_METHOD, HEADER, params, success,errMsg)
}
var POST_METHOD = "POST"

function post(api, params, success,errMsg){
    request(api, POST_METHOD, HEADER, params, success,errMsg)
}
var DEL_METHOD = "DELETE"

function del(api, params, success,errMsg){
    request(api, DEL_METHOD, HEADER, params, success,errMsg)
}

function b64EncodeUnicode(str) {
    return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(match, p1) {
        return String.fromCharCode('0x' + p1);
    }));
}

function b64DecodeUnicode(str) {
    return decodeURIComponent(atob(str).split('').map(function(c) {
        return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
    }).join(''));
}



module.exports = {
    GET: get,
    POST: post,
	DEL: del
}

export const GET = get;
export const POST = post;
export const DEL = del;